package com.example.xgakj.mvp_demo.mvp.module;

import android.widget.Toast;

import com.example.xgakj.mvp_demo.App;
import com.example.xgakj.mvp_demo.R;
import com.example.xgakj.mvp_demo.entity.PostInfo;
import com.example.xgakj.mvp_demo.manage.RetrofitManager;
import com.example.xgakj.mvp_demo.utils.CommonUtil;
import com.socks.library.KLog;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017-07-17.
 */

public class LoginInteraction {
    private NetCallback netCallback;
    public LoginInteraction(NetCallback callback) {
        netCallback=callback;
    }

    public void login(String user, String passWord){
        RetrofitManager.getInstance().getPostInfo(user, passWord)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (!CommonUtil.isNetworkAvailable()) {
                            Toast.makeText(App.getAppContext(), R.string.toast_network_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PostInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                       netCallback.onSubscribe(d);
                    }
                    @Override
                    public void onNext(PostInfo value) {
                        netCallback.onSuccess(value);
                    }

                    @Override
                    public void onError(Throwable e) {
                    netCallback.onError(e);
                    }

                    @Override
                    public void onComplete() {
                        KLog.d("onComplete");
                    }
                });
    }
    public  interface NetCallback{
        void onSuccess(PostInfo value);
        void onError(Throwable e);
        void onSubscribe(Disposable d);
    }
}
